class DataUtils::DBObject
    class << self; attr_reader :table_name end
    @table_name = nil
    attr_reader :id
    def initialize(params)
        @id = params[:id]
    end
    def self.table_name()
        return @table_name ? @table_name : DataUtils.pluralize(self.class_name).downcase
    end
    def self.build(result)
        return nil if(result.nil?)
        params = {}
        fields = result.fields
        fields.each_index do |i|
            params[fields[i].to_sym] = result[i]
        end
        return self.new(params)
    end
    def self.find(params = nil, extra = nil)
        result_set = DataUtils.db.execute("SELECT * FROM #{self.table_name()} WHERE #{self.to_where_clause(params)} #{extra}", params)
        results = []
        result_set.each do |result|
        	results << self.build(result)
        end
        return results
    end
    def self.find_first(params = nil)
    	results = find(params, "LIMIT 1")
    	return results[0]
    end
    def self.find_or_create(params)
        db_obj = find(params)
        return db_obj[0] if(!db_obj.nil?)
        return insert(params, true)
    end
    def self.insert(params, return_obj = false)
        DataUtils.db.execute("INSERT INTO #{self.table_name()} #{self.to_insert_clause(params)}", params)
        return find(params)[0] if(return_obj)
    end
    def self.exists?(params)
        return !find(params).nil?
    end
    
    
    private
    def self.to_where_clause(params)
    	return "1 = 1" if(params.nil?)
        param_arr = []
        params.keys.each do |k|
            param_arr << "#{k} = :#{k}"
        end
        return param_arr.join(" AND ")
    end
    
    def self.to_insert_clause(params)
        values = params.keys.inspect.gsub('[', '(')
        values.gsub!(']', ')')
        return "(#{params.keys.join(',')}) VALUES #{values}"
    end
end
